package com.vina.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import com.google.apphosting.api.DatastorePb.GetRequest;
import com.vina.domain.Blog;
import com.vina.persistence.PMF;
import com.vina.utils.Utils;
import com.vina.web.thymeleaf.TemplateEngineUtil;

public class BlogHandlerServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
private static TemplateEngine te;
	
	public BlogHandlerServlet(){
		super();
		te = TemplateEngineUtil.getInstance().getEngine();
	}
	
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        doService(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
//    		
//    	PrintWriter writer = response.getWriter();
//    	String title = request.getParameter("title");
//    	String content = request.getParameter("content");
//    	System.out.println(title+","+content);
//    	writer.write(content);
//    	writer.close(); will commit the response.
//    	response.sendRedirect("/blog/list");
//    	return;
    }

    protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       Blog blog = new Blog();
       blog.setTitle(request.getParameter("title"));
       blog.setContent(request.getParameter("content"));
       blog.setDate(Calendar.getInstance().getTime());
       
       PersistenceManager pm = PMF.get().getPersistenceManager();
       try{
    	   pm.makePersistent(blog);
       }finally{
//    	   pm.close();
       }
       
       Query q = pm.newQuery(Blog.class);
       q.setOrdering("date desc");
       
       List<Blog> results = null;
       
       try{
    	   results = (List<Blog>)q.execute();
    	   
           for(Blog b:results){
        	   System.out.println("------BlogHandler------");
        	   System.out.println(b.toString());
           }
       }finally{
    	   q.closeAll();
    	   pm.close();
       }
       
       PrintWriter writer = response.getWriter();
       writer.write("Yes,ok!");
       writer.close();
    }

}
